using Game.Core;
using Game.Main.Model;
using Game.Main.View;
using Game.Manager;
using Game.XH;
using UnityEngine;

namespace Game.Component
{
	public class CTBedItem : BaseItem
	{
		private enum State
		{
			Static = 0,
			Running = 1
		}

		private float LEFT_X = -1.8f;

		private float RIGHT_X;

		public bool isPlayAnim;

		private State state;

		private float curVal;

		private float targetVal;

		private float timer;

		private CTItem ct;

		public override void Init(ItemArchiveData data)
		{
			base.Init(data);
		}

		protected override void LateUpdate()
		{
			base.LateUpdate();
			if (!isPlayAnim)
			{
				return;
			}
			timer += Time.deltaTime;
			model.SetLocalX(Mathf.Lerp(curVal, targetVal, timer));
			if (!(timer >= 1f))
			{
				return;
			}
			isPlayAnim = false;
			if (state == State.Running)
			{
				if (childItems.Count > 0)
				{
					IsCTRunning(true);
				}
			}
			else
			{
				IsCTRunning(false);
			}
		}

		public override bool AttachItem(BaseItem item, DepthType depthType, AttachType attachType, bool updatePosition)
		{
			bool flag = base.AttachItem(item, depthType, attachType, updatePosition);
			if (flag && childItems.Count > 0 && state == State.Running)
			{
				IsCTRunning(true);
			}
			return flag;
		}

		public override void ReleaseAttachItem(BaseItem item)
		{
			base.ReleaseAttachItem(item);
			if (childItems.Count <= 0)
			{
				IsCTRunning(false);
			}
		}

		public void ClickButton()
		{
			if (isPlayAnim)
			{
				Singleton<AudioManager>.Instance.PlaySound("sound_error");
				return;
			}
			if (state == State.Static)
			{
				curVal = RIGHT_X;
				targetVal = LEFT_X;
				SetState(State.Running);
			}
			else
			{
				curVal = LEFT_X;
				targetVal = RIGHT_X;
				IsCTRunning(false);
				SetState(State.Static);
			}
			Singleton<AudioManager>.Instance.PlaySound("sound_ct_bed_1");
			isPlayAnim = true;
			timer = 0f;
		}

		private void SetState(State val)
		{
			if (state != val)
			{
				state = val;
			}
		}

		private void IsCTRunning(bool val)
		{
			if (ct == null)
			{
				BaseItem itemByScriptType = Singleton<Scene>.Instance.GetItemByScriptType(128);
				if (itemByScriptType != null)
				{
					ct = (CTItem)itemByScriptType;
				}
			}
			if (ct != null)
			{
				ct.IsRunning(val);
			}
		}
	}
}
